﻿using System;
using System.Web.Mvc;
using Data;
using Web.Filters;
using Models;

namespace Web.Controllers
{
    public class AccountControllController : BaseController
    {
        //
        // GET: /AccountControll/

        [UserAuth]
        [UpdateLastVisit]

        public ActionResult Index(int? page = null)
        {

            var dbNews = new NewsData();
            var newsList = dbNews.GetNews(author: GetFormsAuthenticationTicket().Name);
            if (newsList != null)
            {
                var pager = new Pager(newsList.Count, Request.Url.LocalPath, page);
                if (pager.Check() == null)
                {
                    Redirect(Request.Url.LocalPath);
                }
                ViewBag.pager = pager;
                return View(newsList);

            }

            return View();
        }

        [UserAuth]
        [UpdateLastVisit]
        public ActionResult Pm(string cmd, int? id)
        {
            if (cmd == null)
            {
                var dbPm = new PrivateMessageData();
                var dbUsers = new UsersData();
                var messageList = dbPm.Receive(id: id,
                                               receiverId:
                                                   dbUsers.GetUsers(login: GetFormsAuthenticationTicket().Name)[0].Id);

                return View("pmReceive", messageList);
            }
            return View("pmReceive");
        }

        [UserAuth]
        [UpdateLastVisit]
        public ActionResult SendPm(int id)
        {
            var dbUsers = new UsersData();

            var pm = new PrivateMessage
                         {
                             Receiver = dbUsers.GetUsers(id)[0],
                             Sender = dbUsers.GetUsers(login:GetFormsAuthenticationTicket().Name)[0]
                         };
            ViewBag.ReceiverLogin = pm.Receiver.Login;
            return View(pm);
        }

        [UserAuth]
        [UpdateLastVisit]
        [HttpPost]
        public ActionResult SendPm(PrivateMessage model,int id)
        {
            if(ModelState.IsValid)
            {
                model.SendDate = DateTime.Now;
                var dbPm = new PrivateMessageData();
                dbPm.Send(model);
                ViewBag.Message = "Successfully sended";
                return View(model);
            }
            
            return SendPm(id);
        }

}
}
